import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
  {
    path: "",
    redirect: "/home",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login.vue"),
  },
  {
    path: "/",
    component: () => import("@/views/layout.vue"),
    redirect: "home",
    children: [
      {
        path: "home",
        name: "home",
        component: () => import("@/views/home.vue"),
      },
      {
        path: "users",
        name: "users",
        component: () => import("@/views/users.vue"),
      },
      {
        path: "carousel/list",
        component: () => import("@/views/carouselList.vue"),
      },
      {
        path: "carousel/add",
        component: () => import("@/views/carouselAdd.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  const authorization = localStorage.getItem("authorization");

  if (authorization) {
    if (to.path === "/login") {
      next({ path: "/home" });

      return;
    }

    next();
  } else {
    if (to.path !== "/login") {
      next({ path: "/login" });

      return;
    } else {
      next();
    }
  }
});

export default router;
